/**
 * Created with IntelliJ IDEA.
 * Description:
 * User: 26727
 * Date: 2024-02-03
 * Time: 20:52
 */
class Solution {
    public String tree2str(TreeNode root) {
        if(root == null) {
            return null;
        }
        StringBuilder stringBuilder = new StringBuilder();
        tree2strChild(root,stringBuilder);

        return stringBuilder.toString();
    }

    public void tree2strChild(TreeNode root, StringBuilder stringBuilder) {
        if(root == null) {
            return;
        }
        stringBuilder.append(root.val);
        if(root.left != null) {
            stringBuilder.append("(");
            tree2strChild(root.left,stringBuilder);
            stringBuilder.append(")");
        }else {
            if(root.right != null) {
                stringBuilder.append("()");
            }else {
                return;
            }
        }

        if(root.right != null) {
            stringBuilder.append("(");
            tree2strChild(root.right,stringBuilder);
            stringBuilder.append(")");
        }else {
            return;
        }
    }
}
